package com.example.docking.util;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class HmacSha256Example {
    public static String hmacSha256Test(String data, String key) {
        try {
            // 创建 HMAC - SHA256 算法的 Mac 实例
            Mac hmacSha256 = Mac.getInstance("HmacSHA256");
            // 生成 HMAC - SHA256 密钥
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            // 初始化 Mac 实例
            hmacSha256.init(secretKeySpec);
            // 对输入的数据进行加密
            byte[] hmacData = hmacSha256.doFinal(data.getBytes(StandardCharsets.UTF_8));
            // 将加密后的字节数组转换为十六进制字符串
            return bytesToHex(hmacData);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }

    public static void main(String[] args) {
        String data = "961a71620a3fb7ee8927eae92deeab97";
        String key = "306503";
        String hmacResult = hmacSha256Test(data, key);
        System.out.println("HMAC - SHA256 加密结果（十六进制）: " + hmacResult);
    }
}    